﻿package com.thorqq.magictimer.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;

import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.core.TimerAbs;
import com.thorqq.magictimer.util.Util;

/**
 * 发送短信
 * 
 */
public class ActionSendSMS extends TAction
{
    private static final long serialVersionUID = -5256248883647483991L;

    protected final int PARAM_NUM = 2;
    protected final String PHONENUMBER_HYPHEN = ";"; // 用来分隔多个号码
    protected final String PHONENUMBER_SEPARATOR = "\\;"; // 用来分隔多个号码
    
    protected final String PHONENUMBER_NAME_SEPARATOR = "[\\<\\>]";

    public static final String SMS_SEND_ACTIOIN = "com.thorqq.magictimer.SMS_SEND";
    public static final String SMS_DELIVERED_ACTION = "com.thorqq.magictimer.SMS_DELIVERED";

//    private Vector<String> mPhoneNumber = new Vector<String>();
    protected Map<String, String> mPhoneNumber = new HashMap<String, String>();
    protected String mPhoneNumberString;
    protected String mContent;

    public ActionSendSMS(int id, int execOrder, String actionType, String param)
    {
        super(id, execOrder, actionType, param);
    }

    @Override
    public boolean run(Context context, TimerAbs timer)
    {
        this.paramToString();
        
        SmsManager smsManager = SmsManager.getDefault();
        ArrayList<String> parts = smsManager.divideMessage(mContent);
        ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();      
        ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();      
        
        Intent itSend = new Intent(SMS_SEND_ACTIOIN);
        Intent itDeliver = new Intent(SMS_DELIVERED_ACTION);
        
        sentIntents.add(PendingIntent.getBroadcast(context.getApplicationContext(), 0, itSend, 0));
        deliveryIntents.add(PendingIntent.getBroadcast(context.getApplicationContext(), 0, itDeliver, 0));
                
        for (String key : mPhoneNumber.keySet())
        {
            try
            {
                smsManager.sendMultipartTextMessage(key, null, parts, sentIntents, deliveryIntents);
                Util.log("Send sms to " + mPhoneNumber.get(key) + "|" + key);
            } 
            catch (Exception e)
            {
                Util.log_ex(e);
            }
        }

        return true;
    }

    @Override
    public String getName()
    {
        return "发送短信";
    }

    @Override
    public String getDescription()
    {
        return null;
    }

    public void setPhoneNumber(Map<String, String> m)
    {
        mPhoneNumber.clear();
        mPhoneNumber.putAll(m);
        
        makePhoneNumberString();
    }

    public void addPhoneNumber(String phonenumber, String displayname)
    {
        if(mPhoneNumber == null)
        {
            mPhoneNumber = new HashMap<String, String>();
        }
        mPhoneNumber.put(phonenumber, displayname);
        
        makePhoneNumberString();
    }

    public Map<String, String> getPhoneNumber()
    {
        return mPhoneNumber;
    }
    
    public String getPhoneNumberString()
    {
        return mPhoneNumberString;
    }
    
    public void setPhoneNumberString(String s)
    {
        mPhoneNumberString = s.trim();
        
        if (mPhoneNumberString != null)
        {
            //先按发送对象分开
            String[] person = Util.splitParames(mPhoneNumberString, PHONENUMBER_SEPARATOR);
            mPhoneNumber.clear();
            for (int i = 0; i < person.length; i++)
            {
                //按<分割
                String[] info = Util.splitParames(person[i], PHONENUMBER_NAME_SEPARATOR);
                if(info.length == 1 && isNum(info[0]) && info[0].length() > 0)
                {
                    mPhoneNumber.put(info[0], "");
                }
                else if(info.length == 2 && isNum(info[1]) && info[1].length() > 0)
                {
                    mPhoneNumber.put(info[1], info[0]);
                }
                else
                {
                    Util.log("Error phonenumber: " + mPhoneNumberString);
                }
            }
        }
        
    }
    
    private void makePhoneNumberString()
    {
        StringBuffer sff = new StringBuffer();
        for (String key : mPhoneNumber.keySet()) 
        {
            sff.append(mPhoneNumber.get(key))
                  .append("<")
                  .append(key.trim())
                  .append(">")
                  .append(PHONENUMBER_HYPHEN);
        }
        mPhoneNumberString = sff.toString(); 
    }

    public void setContent(String c)
    {
        mContent = c.trim();
    }

    public String getContent()
    {
        return mContent;
    }
    

    public void setParam(Map<String, String> m, String c)
    {
        this.setPhoneNumber(m);
        this.setContent(c);

        this.paramToString();
    }

    @Override
    public boolean parseStringParam()
    {
        if (mParam == null)
        {
            return true;
        }

        String[] array = Util.splitParames(mParam);
        if (array.length != PARAM_NUM)
        {
            Util.log("TimeParam setParam error. param = " + mParam);
            return false;
        }

        String tmp = array[0];
        if (tmp != null)
        {
            setPhoneNumberString(tmp);
        }

        mContent = array[1];

        return true;
    }

    @Override
    public String paramToString()
    {
        StringBuffer sff = new StringBuffer();
        
        sff.append(mPhoneNumberString).append(Util.PARAMES_HYPHEN)
           .append(mContent);

        return super.mParam = sff.toString();
    }

    private boolean isNum(String str)
    {
        return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
    }

}
